importPackage(android.speech.tts);
importClass(java.util.Locale);

var tts

function speak(text) {
    if (!tts) {
        tts = new TextToSpeech(context, function (status) {
            if (status != tts.SUCCESS) {
                console.log("初始化TTS识别: " + status);
                exit();
            }
            var r = tts.setLanguage(Locale.CHINA);
            if (r < 0) {
                console.log("不支持该语言: " + r);
                exit();
            }
            console.log("TTS初始化成功");
        });
    }
    tts.speak(text, tts.QUEUE_ADD, null)
}



// 解锁
function unlock() {
    if (!device.isScreenOn()) {
        device.wakeUp();
        let width = device.width;
        let height = device.height;

        swipe(200, (height / 5) * 4, 400, height / 5, 201);
        sleep(1000);
        let passwd = "0423";
        for (let id = 0; id < passwd.length; id++) {
            let keynum = passwd[id];
            click(keynum);
        }
        sleep(1000);
    }
}

// 定时任务
// {0: 工作日，1：周末，2：节假日}
function isWorkDay() {
    let now = new Date()
    let year = now.getFullYear()
    let month = now.getMonth() + 1
    let day = now.getDate()

    let obj
    try {
        obj = JSON.parse(files.read('./2024.json'))
    } catch (error) {
        return false
    }

    if (month < 10) month = '0' + month.toString()
    if (day < 10) day = '0' + day.toString()

    now = `${year}-${month}-${day}`
    let type
    // for (const oneday in obj) {
    for(let i=0; i<obj.length; i++) {
        if(obj[i].day == now){
            console.log(obj[i].type, )
        }
    }
    console.log(now, type)
}

// 启动miui的app
function startMIUIApp(desc, page) {
    // page:    -1, 0, 1, 2
    home();
    sleep(1000);
    // page -> 0
    home();
    sleep(1000);
    let x1, y1, x2, y2;
    if (page > 0) {
        // 往左划动
        x1 = 960;
        y1 = 1284;
        x2 = 140;
        y2 = y1;
    } else {
        x1 = 140;
        y1 = 1284;
        x2 = 960;
        y2 = y1;
    }

    for (i = 0; i < page; i++) {
        swipe(x1, y1, x2, y2, 300);
        sleep(500);
    }
    let e = packageName("com.miui.home")
        .className("android.widget.RelativeLayout")
        .desc(desc)
        .findOnce();
    if (e) {
        console.log("启动", desc);
        e.click();
    } else {
        console.log("无法找到app: ", desc);
    }
}

function clickBounds(selector) {
    if(!selector) return
    if (selector.exists()) {
        let bounds = selector.findOne(1000).bounds()
        click(bounds.centerX(), bounds.centerY())
        sleep(1000)
    }
}

// exports.unlock = this.unlock
// exports.timing = this.timing
module.exports = {
    unlock,
    isWorkDay,
    startMIUIApp,
    speak,
    clickBounds,
};
